
/**
 * @description  : 请求文件
 * @descriptionDetail : 请求文件
 * @copyright    : 浙江烟草
 * @author       : mc
 * @create       : 2022-10-04 16:47:51
 */
const env = process.env.VUE_APP_ENV;
function initReq(data, url, method, header) {
  return new Promise((resolve, reject) => {
    uni.request({
      url: url,
      data: data,
      header: header,
      method: !method ? "POST" : method,
      success: (response) => {
        if (response.statusCode === 200) { // 服务端返回的状态码不等于200，则reject()
          resolve(response.data);
        } else if ((response.statusCode + '').startsWith('40') || (response.statusCode + '')
          .startsWith('50')) {
          if(response.data && response.data.msg){
            return resolve(response.data);
          }else{
            return reject("服务器繁忙,请稍后再试（错误码" + response.statusCode + "）!");
          }
        } else {
          reject('服务器繁忙,请稍后再试!');
        }
      },
      fail: (err) => {
        console.log(err);
        if (err.errMsg) {
          if (err.errMsg.indexOf('timeout') != -1) {
            reject('连接超时,请稍后再试!');
            return;
          }
        }
        reject("服务器访问失败!");
      },
    })
  });
}
// 去除URL中的参数值为null或undefined的 zyf 2022-10-04  start
function removeNullUndefinedParams(url) {
  const urlObj = new URL(url);
  const params = urlObj.searchParams;
  // 遍历所有参数并去除为null或undefined的
  params.forEach((value, key) => {
    if (value === null || value === 'undefined') {
      params.delete(key);
    }
  });
  // 重新设置URL对象的search部分
  urlObj.search = params.toString();
  // 返回去除参数后的URL字符串
  return urlObj.toString();
}
// 去除URL中的参数值为null或undefined的 zyf 2022-10-04  end

function doReq(data, url, method, contentType, headParam) {
  let head = {
    "content-type": !contentType ? "application/json" : contentType,
    "tk": url.indexOf('login') != -1 ? '' : (uni.getStorageSync("tk") || sessionStorage.getItem('tk') || ""),
  };
  if (headParam) {
    Object.keys(headParam).forEach(key => {
      head[key] = headParam[key];
    });
  }
  console.log("接口名：" + url);
  console.log("请求头：" + JSON.stringify(head));
  console.log("请求参数1:" + JSON.stringify(data));
  data = JSON.parse(JSON.stringify(data, (key, val) => {
    return (typeof val === 'undefined' || val == null) ? '' : val
  }));
  console.log("请求参数2:" + JSON.stringify(data));
  let urlStr = removeNullUndefinedParams(url);
  console.log("请求地址：" + urlStr);
  return new Promise((resolve, reject) => {
    uni.request({
      url: urlStr,
      data: data,
      header: head,
      method: url.indexOf('.json') > -1 ? "GET" : (!method ? "POST" : method),
      success: (response) => {
        if (response.statusCode === 200 || (env === 'mock' && response.statusCode ===
					304)) { // 服务端返回的状态码不等于200，则reject()
          return resolve(response.data);
        } else if ((response.statusCode + '').startsWith('40') || (response.statusCode + '')
          .startsWith('50')) {
          if(response.data && response.data.msg){
            return resolve(response.data);
          }else{
            return reject("服务器繁忙,请稍后再试（错误码" + response.statusCode + "）!");
          }
        } else {
          return reject('服务器繁忙,请稍后再试!');
        }
      },
      fail: (err) => {
        console.log(err);
        if (err.errMsg) {
          if (err.errMsg.indexOf('timeout') != -1) {
            reject('连接超时,请稍后再试!');
            return;
          }
        }
        reject("服务器访问失败!");
      },
    })
  });
}

export {
  doReq,
  initReq,
};
